package com.im.gate.codec;


import com.rou.im.framework.core.transfer.MsgHeader;
import com.rou.im.framework.core.transfer.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-04-06 14:35
 */

public class MessageEncoder extends MessageToByteEncoder<Packet> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf out) {
        // 这里会判断消息类型是不是EMPTY类型，如果是EMPTY类型，则表示当前消息不需要写入到管道中
        //获取请求头
        MsgHeader headers = packet.getHeader();
        out.writeShort(headers.getMagicNumber());    // 写入当前的魔数
        out.writeInt(headers.getClientVersion());    // 写入当前的版本号
        out.writeInt(headers.getCmdId());    // 写入当前的命令号
        out.writeInt(headers.getSeq());    // 写入当前的消息序列号
        out.writeInt(packet.getBody().length);
        out.writeBytes(packet.getBody());
    }
}

